package haoi.dt.utils;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.UnknownHostException;

public class ProxyService {
    public static String getProxy(){
        //这里是代理网站
        String url = "http://ip.ipjldl.com/index.php/api/entry?method=proxyServer.tiqu_api_url&packid=0&fa=0&dt=0&groupid=0&fetch_key=&qty=1&time=1&port=1&format=txt&ss=1&css=&dt=0&pro=&city=&usertype=6";
        CloseableHttpClient httpClients = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        try {
            CloseableHttpResponse httpResponse = httpClients.execute(httpGet);
            String result = EntityUtils.toString(httpResponse.getEntity());
            return result;
        } catch (HttpHostConnectException e2){
            System.out.println("获取代理地址超时");
            //等2秒再去请求
            try {
                Thread.sleep(2 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getProxy();
        }
        catch (UnknownHostException e2){
            System.out.println("未知主机,ip.ipjldl.com");
            //等2秒再去请求
            try {
                Thread.sleep(2 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getProxy();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
